<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="/inc/taglib.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>权限权限维护Form</title>
<%@ include file="/inc/head.jsp"%>
<%@include file="/inc/import-zTree-css.jspf"%>
<%@include file="/inc/import-application-js.jspf"%>
</head>
<script type="text/javascript">
	var submitForm = function($dialog, $grid, $pjq) {
		if ($('form').form('validate')) {
			var url;
			if ($(':input[name="id"]').val().length > 0) {
				url = sy.contextPath + '/sys/permission/role/update';
			} else {
				url = sy.contextPath + '/sys/permission/role/create';
			}
			$.post(url, sy.serializeObject($('form')), function(result) {
				if (result.success) {
					$grid.datagrid('load');
					$dialog.dialog('destroy');
				} else {
					$pjq.messager.alert('提示', result.msg, 'error');
				}
			}, 'json');
		}
	};
	$(function() {
		if ($(':input[name="id"]').val().length > 0) {
			parent.$.messager.progress({
				text : '数据加载中....'
			});
			var url = sy.contextPath + '/sys/permission/role/get';
			$.post(url, {
				id : $(':input[name="id"]').val()
			}, function(result) {
				if (result.id != undefined) {
					$('form').form('load', {
						'id' : result.id,
						'role' : result.role,
						'name' : result.name,
						'description' : result.description,
						'show' : result.show
					});
				}
				parent.$.messager.progress('close');
			}, 'json');
		}
	});
</script>
<body>
	<form:form id="editForm" method="post" commandName="m" cssClass="form">
		<fieldset>
			<legend>角色基本信息</legend>
			<table class="table" style="width: 100%;">
				<tr>
					<th>编号</th>
					<td><input name="id" value="${m.id}" readonly="readonly" /></td>
					<th>角色名称</th>
					<td>
					<input name="name" class="easyui-validatebox"
						data-options="required:true" /></td>
				<tr>
					<th>角色标识</th>
					<td><input name="role" class="easyui-validatebox"
						data-options="required:true" /></td>
					<th>详细描述</th>
					<td><input name="description" class="easyui-validatebox"
						data-options="required:true" /></td>
				</tr>
				<tr>
					<th>状态</th>
					<td colspan="3"><form:radiobuttons path="show"
							items="${availableList}" itemLabel="info" itemValue="value"
							cssClass="validate[required]" /></td>
				</tr>
			</table>
		</fieldset>
		<fieldset>
			<legend>授权信息</legend>
			<table width="100%">
				<tr align="center">
					<th>资源信息</th>
					<th>权限信息</th>
					<th>操作</th>
				</tr>
				<tr>
					<td >
						<div class="input-append" title="选择资源">
							<input type="hidden" id="resourceId" value="${target.id}">
							<input type="text" id="resourceName"
								value="${target.name}" readonly="readonly"> <a
								id="selectResourceTree" href="javascript:;"
								class="easyui-linkbutton">选择</a>
						</div>
					</td>
					<td><select id="permissions" multiple="multiple">
							<c:forEach items="${permissions}" var="p">
								<option value="${p.id}" title="${p.description}">${p.name}&nbsp;&nbsp;(${p.permission})</option>
							</c:forEach>
					</select></td>
					<td><a href="javascript:void(0);"
						class="easyui-linkbutton btn-add-resource-permission">添加</a></td>
				</tr>
				<tr>
					<td colspan="4">注意：添加的数据是临时的，还需要点击页面下方的[新增/修改]保存该数据</td>
				</tr>
			</table>
		</fieldset>
		<fieldset>
			<legend>已选择的资源和权限</legend>
			<div id="selectedResourcePermssion">
				<table style="width: 100%;"class="table">
					<thead>
						<tr align="center">
							<th class="check"><input type="checkbox"></th>
							<th width="35%">资源</th>
							<th width="35%">权限</th>
							<th style="width: 20%;">&nbsp;</th>
						</tr>
					</thead>
					<tbody>
						<c:forEach items="${m.resourcePermissions}" var="o">
							<c:if
								test="${esfn:existsResource(o.resourceId, onlyDisplayShow)}">
								<tr>
									<td class="check"><input type="checkbox"></td>
									<td><input type='hidden' id='resourceId_${o.resourceId}'
										name='resourceId' value='${o.resourceId}'> <sys:showResourceName
											id="${o.resourceId}" /></td>
									<td><span style="line-height: 30px"> <c:set
												var="permissionIds" value="" /> <c:set var="count"
												value="0" /> <c:forEach items="${o.permissionIds}"
												var="permissionId">
												<c:if
													test="${esfn:existsPermission(permissionId, onlyDisplayShow)}">
													<c:set var="count" value="${count+1}" />
													<c:set var="permissionIds"
														value="${permissionIds}${count == 1 ? '' : ','}${permissionId}" />
													<c:if test="${status.count > 1}">|</c:if>
													<sys:showPermissionName id="${permissionId}" />
												</c:if>
											</c:forEach>
									</span> <input type='hidden' name='permissionIds'
										value='${permissionIds}'></td>
									<td><a
										class='easyui-linkbutton btn-delete-resource-permission'
										href='javascript:;' onclick='removeResourcePermission(this);'>
											删除
									</a></td>
								</tr>
							</c:if>
						</c:forEach>
					</tbody>
				</table>
			</div>
		</fieldset>
	</form:form>
</body>
<%@include file="/inc/import-zTree-js.jspf"%>
<script type="text/javascript">
	$(function() {
		//
		var resourceTreeId = $.zTree.initSelectTree({
			zNodes : [],
			nodeType : "default",
			fullName : true,
			urlPrefix : "${ctx}/sys/resource",
			async : true,
			asyncLoadAll : true,
			onlyDisplayShow : true,
			lazy : true,
			select : {
				btn : $("#selectResourceTree,#resourceName"),
				id : "resourceId",
				name : "resourceName",
				includeRoot : false
			},
			autocomplete : {
				enable : false
			},
			setting : {
				check : {
					enable : true,
					chkStyle : "checkbox",
					onlyCheckLeaf : false,
					onlySelectLeaf : true
				}
			}
		});
		//
		$(".btn-add-resource-permission").click(function() {
            var resourceIds = $("#resourceId").val().split(",");
            var resourceNames = $("#resourceName").val().split(",");
            var $selectedPermissions = $("#permissions option:selected");
            var permissionIds = $selectedPermissions.map(function() {return this.value;}).get().join(",");
            var permissionNames = $selectedPermissions.map(function() {return this.text;}).get().join(",");

            if(!resourceIds || !resourceIds.length || !resourceIds[0]) {
                parent.$.messager.alert("温馨提示","请选择资源");
                return;
            }
            for(var i=0,len=resourceIds.length;i<len;i++) {
                var resourceId = resourceIds[i];
                if(!resourceId) {
                    continue;
                }
                if($("#resourceId_" + resourceId).size() > 0) {
                    parent.$.messager.alert("温馨提示","您已经选择了此资源，不能重复选择！");
                    return;
                }
            }
            if(!permissionIds) {
            	parent.$.messager.alert("温馨提示",'请选择权限');
                return;
            }
            var template =
                    "<tr>" +
                            "<td class='check'><input type='checkbox'></td>" +
                            "<td>" +
                            "<input type='hidden' id='resourceId_{resourceId}' name='resourceId' value='{resourceId}'>" +
                            "{resourceName}" +
                            "</td>" +
                            "<td>" +
                            "<input type='hidden' name='permissionIds' value='{permissionIds}'>" +
                            "{permissionNames}" +
                            "</td>" +
                            "<td>" +
                            "<a class='easyui-linkbutton btn-delete-resource-permission' href='javascript:void(0);' onclick='removeResourcePermission(this);'>删除</a>" +
                            "</td>" +
                            "</tr>";
            for(var index=0,len=resourceIds.length;index<len;index++) {
                var resourceId = resourceIds[index];
                var resourceName = resourceNames[index];
                if(!resourceId) {
                    continue;
                }
                $("#selectedResourcePermssion .table tbody").append(
                        template.replace(/{resourceId}/g, resourceId)
                                .replace("{resourceName}", resourceName.replace(",", "<br/>").replace(">", "&gt;"))
                                .replace("{permissionIds}", permissionIds)
                                .replace("{permissionNames}", permissionNames)
                );
                alert("xxxxxover");
                //更新表格的全选反选
                $.table.initCheckbox($("#selectedResourcePermssion .table"));
            };
            $.fn.zTree.getZTreeObj(resourceTreeId).checkAllNodes(false);
            $("#resourceId,#resourceName").val("");
            $selectedPermissions.attr("selected", false);
        });

        $.table.initCheckbox($("#selectedResourcePermssion .table"));
        //删除方法
        $(".btn-delete-all-resource-permission").click(function() {
            var checkbox = $.table.getAllSelectedCheckbox($("#selectedResourcePermssion .table"));
            if(!checkbox.length) {
                return;
            }
            parent.$.messager.confirm("确认删除授权资源和权限","确认删除授权的资源和权限吗？",function(r){
                if(r){
                	 checkbox.each(function() {
                         $(this).closest("tr").remove();
                     });
                    }
                });
        });
		//
	});
	function removeResourcePermission(a) {
		parent.$.messager.confirm('询问', '您确定要删除此记录？', function(r) {
			if(r){
				 $(a).closest('tr').remove();
				}
			});
   }
</script>
</html>